package chapter1.thread.account_Lock;

import java.util.Random;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class MoneyTaker extends Thread {
    private final Account ac;
    private static Lock lock = new ReentrantLock();//接口实现类的构造方法
    private static Condition condition = lock.newCondition();


    public MoneyTaker(String name, Account ac) {
        super(name);
        this.ac = ac;
    }

    @Override
    public void run() {
        Random r = new Random();


        while (true) {
            int qu = r.nextInt(200);//0-200,要取的钱数
            System.out.println(getName() + "计划取钱：" + qu);
            try {
                lock.lock();//获取锁
                while (ac.getMoney() < qu) {  //相当于把getMoney，takeAway两个方法变成同步方法？
                    System.out.println(getName() + "发现钱不够,等着,现在余额是" + ac.getMoney());
//                    ac.wait();//等待存钱的人发通知
                    condition.await();
                    System.out.println(getName() + "被喊醒，检查一下钱够不够！");
                }
                ac.takeAway(qu);
                System.out.println(getName() + "取钱" + qu + "成功，现在余额是" + ac.getMoney() + "元");
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                lock.unlock();//释放锁
            }
        }
    }

    public static void notice() {
        lock.lock();
        try {
            condition.signalAll();
        } finally {
            lock.unlock();
        }
    }

}